//
//  STLoginViewController.m
//  赛拓
//
//  Created by 王磊 on 7/31/16.
//  Copyright © 2016 立金所. All rights reserved.
//

#import "STLoginViewController.h"
#import "STCustomTF.h"
#import "STRegisterViewController.h"
#import "STGetBackPwdViewController.h"
#import "STTabbarViewController.h"
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import "STAccountBean.h"
#import "STTabbarViewController.h"
@interface STLoginViewController ()<STBaseViewDelegate>

@property (nonatomic ,strong) STCustomTF *phone;

@property (nonatomic ,strong) STCustomTF *pwd;

@end

@implementation STLoginViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.phone clear];
    
    [self.pwd clear];
    
    [SVProgressHUD popActivity];
}
#define imageView_height 120 * ST_RATE
- (void)initSubviews {
    [super initSubviews];
    
    self.title = @"登录";
    
    CGFloat height = 85 * ST_RATE;
    
    CGFloat left_margin = 40 * ST_RATE;
    
    self.view.backgroundColor = ST_WHITE_COLOR;
    
    [self.imageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(200 * ST_RATE);
        make.right.equalTo(- 200 * ST_RATE);
        make.top.equalTo(120 * ST_RATE);
        make.height.equalTo(imageView_height);
    }];
    
    self.imageView.image = [UIImage imageNamed:@"logo"];
    
    STCustomTF *phone = [STCustomTF instance];
    
    phone.mDelegate = self;
    
    self.phone = phone;
    
    phone.iconImageName = @"手机";
    
    phone.placeHolder = @"请输入手机号";
    
    phone.tid = @"phone";
    
    phone.maxLength = 11;
    
    phone.returnKeyType = UIReturnKeyNext;
    
    [self.view addSubview:phone];
    
    STCustomTF *pwd = [STCustomTF instance];
    
    self.pwd = pwd;
    
    pwd.mDelegate = self;
    
    pwd.tid = @"pwd";
    
    pwd.maxLength = 18;
    
    pwd.iconImageName = @"密码";
    
    pwd.returnKeyType = UIReturnKeyDone;
    
    pwd.placeHolder = @"请输入密码";
    
    pwd.secureTextEntry = true;
    
    [self.view addSubview:pwd];
    
    @WeakObj(self)
    [phone makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(selfWeak.imageView.mas_bottom).offset(120 * ST_RATE);
        make.height.equalTo(height);
        make.left.equalTo(left_margin);
        make.right.equalTo(-left_margin);
    }];
    
    [pwd makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phone.mas_bottom).offset(25 * ST_RATE);
        make.height.equalTo(height);
        make.left.equalTo(left_margin);
        make.right.equalTo(-left_margin);
    }];
    
    CGSize size = [NSString suitToSize:@"注册账号" withSize:CGSizeMake(999, 999) andFont:ST_15_FONT andLineSpacing:3];
    
    UIButton *regist = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.view addSubview:regist];
    
    [regist setTitle:@"注册账号" forState:UIControlStateNormal];
    
    [regist setTitle:@"注册账号" forState:UIControlStateHighlighted];
    
    [regist setTitleColor:ST_167EC0_COLOR forState:UIControlStateNormal];
    
    [regist setTitleColor:ST_167EC0_COLOR forState:UIControlStateHighlighted];
    
    regist.titleLabel.font = ST_15_FONT;
    
    [regist makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwd.mas_left).offset(height / 2);
        make.top.equalTo(pwd.mas_bottom).offset(30 * ST_RATE);
        make.height.equalTo(size.height);
        make.width.equalTo(size.width);
    }];
    
    size = [NSString suitToSize:@"找回密码? " withSize:CGSizeMake(999, 999) andFont:ST_15_FONT andLineSpacing:3];
    
    UIButton *getBackPwd = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.view addSubview:getBackPwd];
    
    [getBackPwd setTitle:@"找回密码?" forState:UIControlStateNormal];
    
    [getBackPwd setTitle:@"找回密码?" forState:UIControlStateHighlighted];
    
    getBackPwd.titleLabel.font = ST_15_FONT;
    
    [getBackPwd setTitleColor:ST_167EC0_COLOR forState:UIControlStateNormal];
    
    [getBackPwd setTitleColor:ST_167EC0_COLOR forState:UIControlStateHighlighted];
    
    [getBackPwd makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(pwd.mas_right).offset(-height / 2);
        make.top.equalTo(pwd.mas_bottom).offset(30 * ST_RATE);
        make.height.equalTo(size.height);
        make.width.equalTo(size.width);
    }];
    
    UIButton *login = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.view addSubview:login];
    
    [login setTitle:@"登录" forState:UIControlStateNormal];
    
    [login setTitle:@"登录" forState:UIControlStateHighlighted];
    
    login.titleLabel.font = ST_16_FONT;
    
    login.backgroundColor = ST_167EC0_COLOR;
    
    login.layer.cornerRadius = height / 2;
    
    [login setTitleColor:ST_WHITE_COLOR forState:UIControlStateNormal];
    
    [login setTitleColor:ST_WHITE_COLOR forState:UIControlStateHighlighted];
    
    [login makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwd.mas_left);
        make.right.equalTo(pwd.mas_right);
        make.top.equalTo(regist.mas_bottom).offset(30 * ST_RATE);
        make.height.equalTo(height);
    }];
    
    
    
    [login addTarget:self action:@selector(loginTriggered) forControlEvents:UIControlEventTouchUpInside];
    
    [regist addTarget:self action:@selector(registTriggered) forControlEvents:UIControlEventTouchUpInside];
    
    [getBackPwd addTarget:self action:@selector(getBackPwdTriggered) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *singleLine = [[UIView alloc]init];
    
    singleLine.backgroundColor = ST_D6D6D6_COLOR;
    
    [self.view addSubview:singleLine];
    
    [singleLine makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwd.mas_left);
        make.right.equalTo(pwd.mas_right);
        make.top.equalTo(login.mas_bottom).offset(130 * ST_RATE);
        make.height.equalTo(1);
    }];
    
    UILabel *label = [[UILabel alloc]init];
    
    label.font = ST_13_FONT;
    
    label.textColor = ST_D6D6D6_COLOR;
    
    label.backgroundColor = ST_WHITE_COLOR;
    
    [self.view addSubview:label];
    
    label.textAlignment = NSTextAlignmentCenter;
    
    CGSize label_size = [NSString suitToSize:@"  第三方账号登录  " withSize:CGSizeMake(999, 999) andFont:ST_13_FONT andLineSpacing:3];
    
    [label makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(label_size.width);
        make.centerY.equalTo(singleLine.mas_centerY);
        make.height.equalTo(label_size.height);
        make.centerX.equalTo(0);
    }];
    label.text = @"第三方账号登录";
    
    CGFloat third_height = 90 * ST_RATE;
    
    UIButton *qq = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [qq setImage:[UIImage imageNamed:@"苹果logo"] forState:UIControlStateNormal];
    
    [self.view addSubview:qq];
    
    UIButton *wechat = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [wechat setImage:[UIImage imageNamed:@"微信logo"] forState:UIControlStateNormal];
    
    [self.view addSubview:wechat];
    
    [qq makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(singleLine.mas_bottom).offset(40 * ST_RATE);
        make.width.equalTo(third_height);
        make.height.equalTo(third_height);
        make.right.equalTo(singleLine.centerX).offset(-40 * ST_RATE);
    }];
    
    [wechat makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(qq.mas_top);
        make.width.equalTo(third_height);
        make.height.equalTo(third_height);
        make.left.equalTo(singleLine.centerX).offset(40 * ST_RATE);
    }];
    
    [qq addTarget:self action:@selector(QQLoginTriggered) forControlEvents:UIControlEventTouchUpInside];
    [wechat addTarget:self action:@selector(wechatLoginTriggered) forControlEvents:UIControlEventTouchUpInside];
}
// 登录
- (void)loginTriggered {
    [self onItemClick:STItemClickTypeLogin withData:nil forIndexPath:nil];
}
// 注册
- (void)registTriggered {
    [self onItemClick:STItemClickTypeRegister withData:nil forIndexPath:nil];
}
// 找回密码
- (void)getBackPwdTriggered {
    [self onItemClick:STItemClickTypePwdBack withData:nil forIndexPath:nil];
}
// qq登录
- (void)QQLoginTriggered {
    [self onItemClick:STItemClickTypeQQLogin withData:nil forIndexPath:nil];
}
// 微信登录
- (void)wechatLoginTriggered {
    [self onItemClick:STItemClickTypeWechatLogin withData:nil forIndexPath:nil];
}
// 按钮点击事件
- (void)onItemClick:(STItemClickType)itemType withData:(id)data forIndexPath:(NSIndexPath *)indexPath {
    switch (itemType) {
        case STItemClickTypeReturnKey:
            if ([data isEqualToString:@"phone"]) {
                
                [self.phone resignFirstResponder];
                
                [self.pwd becomeFirstResponder];
                
            }else {
                
                [self.pwd resignFirstResponder];
                
                [self loginTriggered];
            }
            break;
        case STItemClickTypeLogin: {
            @WeakObj(self)
            if (self.phone.text.length && self.pwd.text.length) {
                
                if ([NSString validPhoneNumber:self.phone.text]) {
                    
                    NSString *pushId = @"123123123";
                    
                    [SVProgressHUD showWithStatus:@"登录中...."];
                    
                    [[STHttpManager getInstance] requestWithUrlString:ST_HTTP_LOGIN andParams:@{@"phoneNum":self.phone.text,@"password":self.pwd.text,@"fromType":@"2",@"pushId":pushId,@"deviceId":deviceId,@"os":deviceOS,@"model":deviceModels,@"resolution":deviceResolution} andStartBlock:^BOOL{
                        return true;
                    } andSuccessBlock:^(NSString *rescode, NSString *msg, NSString *token, NSString *sysTime, id data, NSString *page) {
                        
                        if ([rescode isEqualToString:@"100"]) {
                            
                            STAccountBean *account = [STAccountBean mj_objectWithKeyValues:data];
                            
                            [account save];
                            
                            selfWeak.mDelegate.accountBean = account;
                            
                            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                            
                            STTabbarViewController *tab = [STTabbarViewController instance];
                            
                            [selfWeak presentViewController:tab animated:true completion:nil];
                            
                        } else {
                            
                            [SVProgressHUD showInfoWithStatus:msg];
                        }
                    } andFailureBlock:^BOOL{
                        
                        [SVProgressHUD popActivity];
                        return true;
                    }];
                    
                } else {
                    
                    [SVProgressHUD showInfoWithStatus:@"您输入的不是手机号"];
                }
            } else {
                
                [SVProgressHUD showInfoWithStatus:@"手机号或密码不能为空"];
            }
        }
            break;
        case STItemClickTypeRegister: {
            
            BOOL flag = false;
            for (UIViewController *vc in self.navigationController.childViewControllers) {
                if ([vc isKindOfClass:[STRegisterViewController class]]) {
                    
                    flag = true;
                    
                    [self.navigationController popViewControllerAnimated:true];
                    
                }
            }
            if (!flag) {
                
                STRegisterViewController *regist = [STRegisterViewController instance];
                
                [self.navigationController pushViewController:regist animated:true];
                
                regist.title = @"注册";
            }
        }
            break;
        case STItemClickTypePwdBack: {
            
            STGetBackPwdViewController *getBackPwd = [STGetBackPwdViewController instance];
            
            [self.navigationController pushViewController:getBackPwd animated:true];
        }
            break;
        case STItemClickTypeQQLogin: {
            
            [self loginWithPlatformType:SSDKPlatformTypeQQ];
            
        }
            break;
        case STItemClickTypeWechatLogin: {
            
            [self loginWithPlatformType:SSDKPlatformTypeWechat];
        }
            break;
        default:
            break;
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    
    [self.view endEditing:true];
}

- (void)loginWithPlatformType:(SSDKPlatformType )platformType {
    @WeakObj(self)
    [SSEThirdPartyLoginHelper loginByPlatform:platformType
                                   onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
                                       
                                       //在此回调中可以将社交平台用户信息与自身用户系统进行绑定，最后使用一个唯一用户标识来关联此用户信息。
                                       //在此示例中没有跟用户系统关联，则使用一个社交用户对应一个系统用户的方式。将社交用户的uid作为关联ID传入associateHandler。
                                       
                                       [selfWeak thirdLogin:user forPlatform:platformType];
                                       
                                       associateHandler (user.uid, user, user);
                                   }
                                onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
                                    
                                    if (state == SSDKResponseStateSuccess)
                                    {
                                        
                                    }
                                }];
}
- (void)thirdLogin:(SSDKUser *)user forPlatform:(SSDKPlatformType )platform {
    @WeakObj(self)
    if (user.credential != nil && user.credential.available) {
        
        NSString *plat = platform == SSDKPlatformTypeWechat ? @"1" : @"2" ;
        
        NSString *pushId = @"123123123";
        
        [[STHttpManager getInstance] requestWithUrlString:ST_HTTP_THIRDLOGIN andParams:@{@"type":plat,@"openId":user.uid,@"fromType":@"2",@"pushId":pushId,@"deviceId":deviceId,@"os":deviceOS,@"model":deviceModels,@"resolution":deviceResolution} andStartBlock:^BOOL{
            return true;
        } andSuccessBlock:^(NSString *rescode, NSString *msg, NSString *token, NSString *sysTime, id data, NSString *page) {
            //如果此账号 已经在赛拓平台注册过了 直接登陆成功 如果未注册 执行下面的判断
            if ([rescode isEqualToString:@"100"]) {
                
                STAccountBean *account = [STAccountBean mj_objectWithKeyValues:data];
                [account save];
                
                selfWeak.mDelegate.accountBean = account;
                
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                
                STTabbarViewController *tab = [STTabbarViewController instance];
                
                [selfWeak presentViewController:tab animated:true completion:nil];
            } else if ([rescode isEqualToString:@"106"]) {
                
                STRegisterViewController *regist = [STRegisterViewController instance];
                
                regist.type = plat;
                
                regist.openId = user.uid;
                
                [self.navigationController pushViewController:regist animated:true];
                
                regist.title = @"完善资料";
                
            } else {
                
                [SVProgressHUD showInfoWithStatus:msg];
                
            }
        } andFailureBlock:^BOOL{
            return true;
        }];
    }
}

@end
